<?php

namespace app\wechat\models;

use app\wechat\core\BaseModel;
use cm;
use common\enum\Enum;
use common\models\Circuit;
use common\models\CircuitAddress;
use common\models\OpenCity;
use common\models\PointTime;
use common\models\Shift;
use common\models\Site;
use Yii;
use yii\db\Expression;
use yii\helpers\Url;

class ShiftModel extends BaseModel
{
    /*
    *查询班次
    */
    public function actionSearch(){
        $newtime = time();
        $page = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
        $limit = Cm::$req->post('limit', ['null', 'empty', 'default' => 10]);
        $sid = (int)Cm::$req->post('sid', ['null', 'empty', 'default' => 0]);
        $eid = (int)Cm::$req->post('eid', ['null', 'empty', 'default' => 0]);
        $stype = Cm::$req->post('stype', ['null', 'empty', 'default' => '']);
        $etype = Cm::$req->post('etype', ['null', 'empty', 'default' => '']);
        $time = Cm::$req->post('time', ['null', 'empty', 'default' => date("Y-m-d",$newtime)]);

        $query=Circuit::find()->alias('c')
            ->leftJoin(['ca'=>CircuitAddress::tableName()],['c.id'=>new Expression('ca.circuit_id')])
            ->leftJoin(['st'=>Site::tableName()],['ca.site_id'=>new Expression('st.id')])
            ->leftJoin(['pt'=>PointTime::tableName()],['pt.ca_id'=>new Expression('ca.id')])
            ->leftJoin(['s'=>Shift::tableName()],['s.id'=>new Expression('pt.shift_id')])
            ->andWhere(['c.status'=>Enum::STATUS_NORMAL,'s.status'=>Enum::STATUS_NORMAL,'ca.type'=>CircuitAddress::TYPE_GETON,'ca.is_del'=>CircuitAddress::IS_DEL_NO])
            ->select([
                's.id','s.s_ticket','pt.departuretime','pt.closingtime','pt.presaletime','s.ticket_price','s.circuit_id',
                'c.e_address','c.city_scode','c.city_ecode','c.site_sid','c.site_eid','ca.site_id','ca.address as s_address',
                'pt.id as pt_id','ca.id as ca_id'
                ])
            ->orderBy(['pt.departuretime'=>SORT_ASC,'c.is_hot'=>SORT_DESC]);
        switch ($stype){
            case 'site':
                $where=['=','c.site_sid',$sid];
                break;
            case 'city':
                $city=OpenCity::findOne($sid);
                if($city&&$city->status==Enum::STATUS_NORMAL){
                    $city_code=$city->code;
                }else{
                    $city_code=0;
                }
                $where=['c.city_scode'=>$city_code];
                break;
            default:
                $city=OpenCity::findOne($sid);
                if($city&&$city->status==Enum::STATUS_NORMAL){
                    $city_code=$city->code;
                }else{
                    $city_code=0;
                }
                $where=[
                    'or',
                    ['=','c.site_sid',$sid],
                    ['=','c.city_scode',$city_code]
                ];
                break;
        }
        switch ($etype){
            case 'site':
                if($stype=='site'){
                    $where=[
                        'or',
                        ['and',$where,['=','c.site_eid',$eid]],
                        ['and',['=','ca.site_id',$sid],['=','c.site_eid',$eid]],
                        ['and',$where,['=','ca.site_id',$eid]],
                        ['and',['=','ca.site_id',$sid],['=','ca.site_id',$eid]],
                    ];
                }elseif ($stype=='city'){
                    $where=[
                        'or',
                        ['and',$where,['=','c.site_eid',$eid]],
                        ['and',['=','st.city_code',$city_code],['=','c.site_eid',$eid]],
                        ['and',$where,['=','ca.site_id',$eid]],
                        ['and',['=','st.city_code',$city_code],['=','ca.site_id',$eid]],
                    ];
                }else{
                    $where=[
                        'or',
                        ['and',$where,'c.site_eid'=>$eid],
                        ['and',$where,'ca.site_id'=>$eid]
                    ];
                }
                break;
            case 'city':
                $city=OpenCity::findOne($eid);
                if($city&&$city->status==Enum::STATUS_NORMAL){
                    $e_city_code=$city->code;
                }else{
                    $e_city_code=0;
                }
                if($stype=='site'){
                    $where=[
                        'or',
                        ['and',$where,['=','c.city_ecode',$e_city_code]],
                        ['and',['=','ca.site_id',$sid],['=','c.city_ecode',$e_city_code]],
                        ['and',$where,['=','st.city_code',$e_city_code]],
                        ['and',['=','ca.site_id',$sid],['=','st.city_code',$e_city_code]]
                    ];
                }elseif ($stype=='city'){
                    $where=[
                        'or',
                        ['and',$where,['=','c.city_ecode',$e_city_code]],
                        ['and',['=','st.city_code',$e_city_code],['=','c.city_ecode',$city_code]],
                        ['and',$where,['=','st.city_code',$e_city_code]],
                        ['and',['=','st.city_code',$e_city_code],['=','c.city_ecode',$city_code]],
                    ];
                }else{
                    $where=[
                        'or',
                        ['and',$where,['=','c.city_ecode',$e_city_code]],
                        ['and',$where,['=','st.city_code',$e_city_code]]
                    ];
                }
                break;
            default:
                $city=OpenCity::findOne($eid);
                if($city&&$city->status==Enum::STATUS_NORMAL){
                    $e_city_code=$city->code;
                }else{
                    $e_city_code=0;
                }
                $where_d=[
                    'or',
                    ['=','c.site_eid',$eid],
                    ['=','c.city_ecode',$e_city_code],
                ];
                if($stype=='site'){
                    $where=[
                        'or',
                        ['and',$where_d,$where],
                        ['and',$where_d,['=','ca.site_id',$sid]]
                    ];
                }elseif ($stype=='city'){
                    $where=[
                        'or',
                        ['and',$where_d,$where],
                        ['and',$where_d,['=','st.city_code',$e_city_code]]
                    ];
                }else{
                    $where=[
                        'or',
                        $where_d,
                        $where
                    ];
                }
                break;
        }
        $query->andWhere($where);
        $stime = $time." 00:00:00";
        $etime = $time." 23:59:59";
        $where=[
            'and',
            ['>=','pt.departuretime',$stime],
            ['>','pt.departuretime',date('Y-m-d H:i:s',$newtime)],
            ['<=','pt.departuretime',$etime]
        ];
        $query->andWhere($where);
        $resdata['count']=(clone $query)->count();
        $resdata['data']=Cm::$db->all((clone $query)->limit($limit)->offset(($page - 1) * $limit)->createCommand()->getRawSql());

        if(!empty($resdata['data'])){
            $config = Cm::$db->all("SELECT `key`,`value` FROM config_setting WHERE `group`='sys' AND `key` IN ('sys_service_charge','sys_premium') ");
            $service_charge = 0;
            $premium = 0;
            if(!empty($config)){
                foreach ($config as $key => $value) {
                    if($value['key'] == 'sys_service_charge'){
                        $service_charge = floatval($value['value']);
                    }else if($value['key'] == 'sys_premium'){
                        $premium = floatval($value['value']);
                    }
                }
            }
            $open_city_data=OpenCity::find()
                ->andWhere(['status'=>Enum::STATUS_NORMAL])
                ->select(['name'])
                ->indexBy('code')
                ->column();
            $site_data=Site::find()
                ->andWhere(['status'=>Enum::STATUS_NORMAL])
                ->select(['name'])
                ->indexBy('id')
                ->column();
            foreach ($resdata['data'] as $key => &$value) {
                $departuretime = strtotime($value['departuretime']);
                $value['day'] = date("m月d日",$departuretime);
                $value['hour'] = date("H:i",$departuretime);
                $value['ticket_price'] += $premium+$service_charge;
                $value['s_ticket'] = $this->checkSticket($value['circuit_id'],$value['id'],$value['s_ticket']);
                $value['citysname']=$open_city_data[$value['city_scode']]??'';
                $value['cityename']=$open_city_data[$value['city_ecode']]??'';

                $value['sitetname']=$site_data[$value['site_id']]??'';
                $value['sitesname']=$site_data[$value['site_sid']]??'';
                $value['siteename']=$site_data[$value['site_eid']]??'';

            }
        }
        Cm::$res->susess($resdata);
    }

    /*
    *开单班次详情
    */
    public function actionInfo(){
        $id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
        $pt_id = (int)Cm::$req->post('pt_id', ['null', 'empty', 'default' => 0]);
        $type = (int)Cm::$req->post('type', ['null', 'empty', 'default' => 0]);
        $order_id = (int)Cm::$req->post('order_id', ['null', 'empty', 'default' => 0]);
        if(empty($id)||empty($pt_id)){
            Cm::$res->error('请选择出发线路和班次');
        }
        $point=PointTime::findOne($pt_id);
        $ca_id=$point->ca_id;
        $sql = "SELECT s.id,s.circuit_id,s.min,s.max,s.type,a.mileage,coa.name AS citysname,cob.name AS cityename,
       sa.name AS sitesname,sb.name AS siteename,s.s_ticket,pt.departuretime,pt.closingtime,pt.presaletime,s.ticket_price,
       ca.address as s_address,a.e_address,ca.id as ca_id,ca.site_id as site_sid,a.site_eid
				FROM shift AS s 
				    Inner Join  point_time as pt ON pt.shift_id=s.id
				INNER JOIN circuit a ON s.circuit_id=a.id
				INNER JOIN circuit_address ca ON ca.circuit_id=a.id
                INNER JOIN site sca ON sca.id=ca.site_id 
				INNER JOIN open_city coa ON coa.code=a.city_scode 
				INNER JOIN open_city cob ON cob.code=a.city_ecode
				INNER JOIN site sa ON sa.id=a.site_sid 
				INNER JOIN site sb ON sb.id=a.site_eid 
				WHERE s.id={$id} AND a.status=1 AND s.status=1 AND coa.status=1 AND cob.status=1 AND
				      sa.status=1 AND sb.status=1 AND ca.id={$ca_id} and ca.type=1 AND ca.is_del=1 AND pt.id={$pt_id}";
        $info = Cm::$db->one($sql);
        if(empty($info)){
            Cm::$res->error('该班次未找到');
        }
        $config = Cm::$db->all("SELECT `key`,`value` FROM config_setting WHERE `group`='sys' AND `key` IN ('sys_service_charge','sys_premium') ");
        if($type == 1 && $order_id != 0){
            $passenger = Cm::$db->all("SELECT name,telephone,id_card AS idcard FROM order_passenger WHERE order_id={$order_id} AND status=1");
            /*foreach ($passenger as $key => &$value) {
                $idcardlen = strlen($value['idcard']);
                $value['idcard'] = $idcardlen==15?substr_replace($value['idcard'],"******",4,6):($idcardlen==18?substr_replace($value['idcard'],"*********",4,9):$value['idcard']);
            }*/
            $info['passenger'] = $passenger;
        }else{
            $info['passenger'] = [];
        }
        $info['service_charge'] = 0;
        $info['premium'] = 0;
        if(!empty($config)){
            foreach ($config as $key => $value) {
                if($value['key'] == 'sys_service_charge'){
                    $info['service_charge'] = floatval($value['value']);
                }else if($value['key'] == 'sys_premium'){
                    $info['premium'] = floatval($value['value']);
                }
            }
        }
        $info['ticket_price'] += $info['premium']+$info['service_charge'];
        $info['s_ticket'] = $this->checkSticket($info['circuit_id'],$info['id'],$info['s_ticket']);
        $closingtime = strtotime($info['closingtime']);
        $departuretime = strtotime($info['departuretime']);
        $time = time();
        if($closingtime < $time){
            Cm::$res->error('该班次已停售');
        }
        if($departuretime < $time){
            Cm::$res->error('该班次已发车');
        }
        $info['day'] = date("m月d日",$departuretime);
        $info['hour'] = date("H:i",$departuretime);
        $info['type'] = $info['type'] == 1 ? '固定班' : '流动班';
        $info['s_site'] = Site::findOne($info['site_sid'])->name;
        $info['e_site'] = Site::findOne($info['site_eid'])->name;
        Cm::$res->susess($info);
    }

    /*
    *构造查询条件
    */
    private function getDataWhere($where = "",$sid,$eid,$stype,$etype,$time,$newtime){
        $where = $this->whereTypeId($where,$sid,$stype,'sa','coa');
        $where = $this->whereTypeId($where,$eid,$etype,'sb','cob');
        $stime = $time." 00:00:00";
        $etime = $time." 23:59:59";
        $where .= " AND s.departuretime>='{$stime}' AND s.departuretime>'{$newtime}' AND s.departuretime<='{$etime}' ";
        return $where;
    }

    /*
    *判断起始终点类型的ID查询条件
    */
    private function whereTypeId($where,$id,$type,$sitefield,$cityfield){
        switch ($type) {
            case 'site':
                $where .= empty($id) ? "" : " AND {$sitefield}.id={$id} ";
                break;
            case 'city':
                $where .= empty($id) ? "" : " AND {$cityfield}.id={$id} ";
                break;
            default:
                $where .= empty($id) ? "" : " AND ( {$cityfield}.id={$id} OR {$sitefield}.id={$id} ) ";
                break;
        }
        return $where;
    }
}